(function() {
    'use strict'
    angular.module('moreimg', [])
    //拍照多张照片
.directive('moreImg', ['obtainImg', function(obtainImg) {
        return {
            restrict: 'A',
            scope: {
                name: '=name',
                length: '=length'
            },
            template: '<li ng-show="isshow" ng-repeat="(key, image) in images track by key"><img ng-click="replaceImage(key)" name="image" type="2" img-cache><div ng-click="removeImage(key);" class="ion-ios-close" style="float:right;color:#ccc;margin-left: -11px;margin-top: 2px;font-size: 20px;z-index:99999;position: relative;"/></li><li ng-click="addImage();" ng-hide="ishide"><img ng-src="img/home/emr/Add-photos.png"></li>',
            link: function(scope, element, attr) {
                var imageLenght = scope.length; //假设设置的长度为3,得到指定的上传几张图片
                scope.images = scope.name; //获取图片

                if (imageLenght == undefined || imageLenght == 0) {
                    imageLenght = 1;
                }
                if (scope.images == undefined || scope.images.length == 0) { //当image为空的时候 循环遍历隐藏
                    scope.isshow = false;
                } else { //否则显示
                    scope.isshow = true;
                }

                if (scope.images.length <= imageLenght) { //当images的长度小于设定的长度的时候，现实默认图片
                    scope.ishide = false; //显示默认图片
                } else {
                    scope.ishide = true; //隐藏图片
                }

                scope.$watch('name', function(value) {
                    if (value.length > 0 || value == undefined) { //当定义为数组或者没有定义的时候
                        scope.images = value;
                        if (value.length >= imageLenght) {
                            scope.isshow = true; //集合里面的图片
                            scope.ishide = true; //隐藏图片
                        } else {
                            scope.isshow = true; //集合里面的图片
                            scope.ishide = false; //显示图片
                        }
                        element.attr('name', scope.images);
                        scope.$apply();
                        return;
                    }
                });

                scope.replaceImage = function replaceImage(key) { //替换图片
                    obtainImg.getPicture().then(function(res) { //从最开始添加图片
                        scope.images.splice(key, 1, res); //替换图片
                        element.attr('name', scope.images);
                        scope.$apply();
                    });
                };
                scope.removeImage = function removeImage(key) {
                    scope.images.splice(key, 1); //删除图片
                    scope.ishide = false;
                    if (scope.images.length == 0) {
                        scope.isshow = false;
                    }
                };

                scope.addImage = function addImage() { //添加图片
                    if (imageLenght == 1) { //只上传一张图片
                        obtainImg.getPicture().then(function(res) { //从最开始添加图片 上传一张图片
                            scope.images.splice(0, 0, res); //添加图片
                            element.attr('name', scope.images);
                            scope.$apply();
                            scope.isshow = true; //显示images
                            scope.ishide = true; //隐藏默认图片
                        })
                    } else {
                        obtainImg.getPicture().then(function(res) { //从最开始添加图片 上传多张图片
                            scope.images.splice(0, 0, res); //添加图片
                            element.attr('name', scope.images);
                            scope.$apply();
                            scope.isshow = true; //显示images
                            if (scope.images.length == imageLenght) { //当images的长度小于设定的长度的时候，现实默认图片
                                scope.ishide = true; //隐藏默认图片
                            } else {
                                scope.ishide = false; //隐藏图片
                            };
                        })
                    }
                };
            }
        };

    }])
    //获取照片
    // 图片获取
    .factory('obtainImg', ['$ionicActionSheet', '$cordovaCamera', '$q', '$timeout', function($ionicActionSheet, $cordovaCamera, $q, $timeout) {

        // 相机配置
        var options = {
            quality: 100,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            allowEdit: false,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 450,
            targetHeight: 700,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: false,
            correctOrientation: true
        };

        // 获取图片源
        function getPicture(opt) {
            var q = $q.defer();
            if (opt === 0) {
                options.sourceType = Camera.PictureSourceType.CAMERA;
            } else {
                options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
            }
            document.addEventListener("deviceready", function() {
                $cordovaCamera.getPicture(options).then(function(imageUrl) {
                    q.resolve(imageUrl);
                }, function(err) {
                    q.reject(err);
                });
            }, false);
            return q.promise;
        }

        // 打开actionsheet
        function showAction(opt) {
            opt = opt || 1;
            var q = $q.defer();
            var hideSheet = $ionicActionSheet.show({
                buttons: [{
                    text: '相机'
                }, {
                    text: '图库'
                }],
                // destructiveText: 'Delete',
                titleText: '图片来源',
                cancelText: '取消',
                cancel: function() {},
                buttonClicked: function(index) {
                    hideSheet();
                    getPicture(index).then(function(res) {
                        q.resolve(res);
                    });
                }
            });
            return q.promise;
        }

        return {
            getPicture: showAction
        };
    }])
    //图片缓存]
    .directive('imgCache', ['FileService', '$timeout', '$filter', function(FileService, $timeout, $filter) {
        return {
            restrict: 'A',
            scope: {
                name: '=name',
                type: '=type'
            },
            link: function(scope, element, attr) {
                element.attr('src', $filter('IMG')(scope.type));
                $timeout(function() {
                    scope.$apply();
                });

                var fileUrl;
                if (ionic.Platform.isIOS()) {
                    fileUrl = cordova.file.documentsDirectory;
                }
                if (ionic.Platform.isAndroid()) {
                    fileUrl = cordova.file.dataDirectory;
                }
                scope.$watch('name', function(data) {
                    if (data) {
                        if (data.length > 100) {
                            element.attr('src', 'data:image/jpeg;base64,' + data);
                            $timeout(function() {
                                scope.$apply();
                            });
                            return
                        }
                        var imageName = data.substring(data.lastIndexOf('/') + 1, data.length); //截取最后一个/后面的数字的字符
                        FileService.query(imageName, data, fileUrl).then(function(res) {
                            element.attr('src', res.data);
                            $timeout(function() {
                                scope.$apply();
                            });
                        });
                    }
                });
            }
        };
    }])

    .factory('FileService', ['$q', '$cordovaFile', '$cordovaFileTransfer', '$timeout', '$cordovaNetwork', function($q, $cordovaFile, $cordovaFileTransfer, $timeout, $cordovaNetwork) {
        function CheckThenDownloadFile(imageName, url, fileUrl) { //imageName为图片的名称， url为图片的路径
            var q = $q.defer();
            //判断是否有这个文件
            $cordovaFile.checkFile(fileUrl, imageName + '.png').then(function(success) {
                q.resolve({
                    data: success.nativeURL
                });
            }, function(error) {
                //没有这个文件，则缓存这个图片
                if ($cordovaNetwork.isOnline()) { //当有网络的时候,先从网络上面拿,拿到了缓存
                    var targetPath = fileUrl + imageName + ".png";
                    $cordovaFileTransfer.download(url, targetPath, {}, true).then(function(result) { //当缓存成功的时候
                        q.resolve({
                            data: result.nativeURL
                        });
                    }, function(err) {
                        q.resolve({
                            data: url
                        });
                    });
                } else {
                    q.reject({
                        data: './img/mine/iconfont-moretouxiang.png'
                    });
                }
            });
            return q.promise;
        };

        return {
            query: CheckThenDownloadFile
        };

    }]);
})();